<script lang="ts" setup>
import type { RowType } from '../../types';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { postLinks, putLink } from '#/api/admin/links';

const [Form, formApi] = useVbenForm({
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    },
    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'score',
      label: '积分',
      rules: 'required',
    },
    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'coin',
      label: '金币',
      rules: 'required',
    },
    {
      component: 'Select',
      defaultValue: '_blank',
      componentProps: {
        placeholder: '请选择',
        options: [
          {
            label: '不限',
            value: 0,
          },
          {
            label: '天',
            value: 1,
          },
          {
            label: '小时',
            value: 2,
          },
          {
            label: '永久',
            value: 3,
          },
        ],
      },
      fieldName: 'cycle_type',
      label: '周期类型',
    },

    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'cycle_time',
      label: '周期时间',
    },
    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'reward_number',
      label: '奖励次数',
    },
  ],
  showDefaultActions: false,
});
const [Modal, formModalApi] = useVbenModal({
  fullscreenButton: false,
  onCancel() {
    formModalApi.close();
  },
  onConfirm: async () => {
    await formApi.validateAndSubmitForm();
    formModalApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const values: RowType = formModalApi.getData();
      if (values) {
        formApi.setValues(values);
      }
    }
  },
});

async function onSubmit(values: Record<string, any>) {
  function showMsg(msg: string) {
    message.success(msg);
    formModalApi.setData({ isUpdata: true });
  }
  if (values.id) {
    const { msg } = await putLink(values);
    showMsg(msg);
  } else {
    const { msg } = await postLinks(values);
    showMsg(msg);
  }
}
</script>
<template>
  <Modal class="w-3/5">
    <Form />
  </Modal>
</template>

<style lang="scss" scoped></style>
